package com.lds.register.center.client.heartbeat.service;

import com.lds.management.center.common.model.dto.ResultDTO;
import com.lds.management.center.common.util.RestUtil;
import com.lds.management.center.common.util.ScheduledUtil;
import com.lds.register.center.client.common.model.request.HeartbeatRequest;
import com.lds.register.center.client.properties.RegisterCenterClientProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;

@Slf4j
public class DefaultHeartbeatService implements HeartbeatService {
    private final Long appId;
    private final Long appInstanceId;

    private final RegisterCenterClientProperties PROPERTIES;
    private final String URL;
    private final ParameterizedTypeReference<ResultDTO<Boolean>> REFERENCE = new ParameterizedTypeReference<ResultDTO<Boolean>>() {};

    public DefaultHeartbeatService(Long appId, Long appInstanceId, RegisterCenterClientProperties properties) {
        this.appId = appId;
        this.appInstanceId = appInstanceId;

        this.PROPERTIES = properties;
        this.URL = PROPERTIES.getUrl() + "/api/remote/app_instance/heartbeat";
    }

    @Override
    public void keepHeartbeat() {
        ScheduledUtil.scheduled(PROPERTIES.getHeartbeatIntervalSeconds(), this::execute);
    }

    private void execute() {
        ResultDTO<Boolean> resultDTO = RestUtil.post(URL, new HeartbeatRequest(appId, appInstanceId), REFERENCE);
        if (!ResultDTO.isSuccess(resultDTO)) {
            log.warn("心跳续约失败. cause={}", resultDTO.getMessage());
        }
    }
}
